import React, { useEffect, useState, useRef } from 'react'
import { Space, Table, Button, Tag, Modal, Checkbox, Form, Input } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { DataType } from './table.d'
import { fetchUserList, fetchUserDelete, fetchUserUpdate } from 'api'
/**
 *
 * 1. form表单中：button htmlType="submit" dom获取
 *
 * 2. form表单放在弹出框中，原表单的submit按钮就不能用了，只能使用弹出框的按钮
 * 但是弹出框的确定按钮没有这个提交from表单内容的属性，所以，需要form的实例来辅助获取表单内容
 *
 *
 */
const Article = () => {
  // form表单的实例 帮助form表单使用js的方式 获取 表单数据或者 设置 表单数据
  const [form] = Form.useForm()
  const [record, setRecord] = useState<any>()
  // page, size
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(0)
  // const [opt, setOpt] = useState<any>({ page: 1, size: 5 })
  // ⭐️：动态数据且不参与render的数据，可以使用useRef定义，因为他定义的是同步数据
  const options = useRef<any>({ page: 1, size: 5 })

  const [isModalOpen, setIsModalOpen] = useState(false)

  const fetchData = async () => {
    const response = await fetchUserList(options.current)
    console.log('respibse:', response.data.data)
    const list = response.data.data
    list.data.forEach((item: any) => {
      item.key = item.id
    })
    setTotal(list.total)
    setList(list.data)
  }
  const onFinish = (values: any) => {
    console.log('Success:', values)
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  const handleDelete = async (data: any) => {
    const res = await fetchUserDelete(data)
    fetchData()
  }

  useEffect(() => {
    fetchData()
  }, [])

  const columns: ColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'cname',
      key: 'cname',
    },
    {
      title: 'ip地址信息',
      dataIndex: 'ip',
      key: 'ip',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    // {
    //   title: 'Tags',
    //   key: 'tags',
    //   dataIndex: 'tags',
    //   render: (_, { tags }) => (
    //     <>
    //       {tags.map((tag) => {
    //         let color = tag.length > 5 ? 'geekblue' : 'green'
    //         if (tag === 'loser') {
    //           color = 'volcano'
    //         }
    //         return (
    //           <Tag color={color} key={tag}>
    //             {tag.toUpperCase()}
    //           </Tag>
    //         )
    //       })}
    //     </>
    //   ),
    // },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              //调用弹出框
              // 调用弹出框，就把需要编辑的数据，回显到对应的input
              showModal()
              form.setFieldsValue({ ...record }) // 异步更新
            }}
          >
            编辑
          </a>
          <a onClick={() => handleDelete(record)}>删除</a>
        </Space>
      ),
    },
  ]

  const onChange = (current: number) => {
    console.log('data:', current)
    options.current.page = current
    fetchData()
  }

  const showModal = () => {
    setIsModalOpen(true)
  }

  // 弹出框的确定按钮 fetchUserUpdate
  const handleOk = async () => {
    // 更新数据接口 如何获取更新后的数据，
    console.log('record:', form.getFieldsValue())
    // 克隆数据，放置数据受影响
    const data = await fetchUserUpdate(form.getFieldsValue())
    console.log('data:', data)
    setIsModalOpen(false)
    // 重新更新数据
    fetchData()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  return (
    <div>
      {/* modal弹出框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="ID" name="id">
            <Input disabled />
          </Form.Item>
          <Form.Item label="姓名" name="cname">
            <Input />
          </Form.Item>
          <Form.Item label="IP" name="ip">
            <Input />
          </Form.Item>
          <Form.Item label="地址" name="address">
            <Input />
          </Form.Item>
          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          {/* <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item> */}
        </Form>
      </Modal>
      {/*  */}
      <Table
        columns={columns}
        pagination={{
          onChange,
          defaultPageSize: options.current.size,
          defaultCurrent: 1,
          total,
        }}
        dataSource={list}
      />
    </div>
  )
}

export default Article
